package com.zq.myrobot.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.zq.myrobot.R;
import com.zq.myrobot.adapter.ChatMessageAdapter;
import com.zq.myrobot.bean.ChatMessage;
import com.zq.myrobot.util.HttpUtils;
import com.zq.myrobot.util.IatSettings;
import com.zq.myrobot.util.JsonParser;
import com.zq.myrobot.util.PreferenceUtils;
import com.zq.myrobot.util.StringFilterUtil;
import com.zq.myrobot.util.TtsSettings;

public class ChatActivity extends Activity {
	/**
	 * 展示消息的listview
	 */
	private ListView mChatView;
	/**
	 * 文本域
	 */
	private EditText mMsg;
	/**
	 * 语音按钮
	 */
	private TextView tv_yuying;
	private ImageButton btn_yuying;
	/**
	 * 存储聊天消息
	 */
	private List<ChatMessage> mDatas = new ArrayList<ChatMessage>();
	/**
	 * 适配器
	 */
	private ChatMessageAdapter mAdapter;

	Context context;
	boolean isyuying = true;

	// 语音听写对象
	private SpeechRecognizer mIat;
	// 语音听写UI
	private RecognizerDialog iatDialog;
	// 听写结果内容
	private EditText mResultText;

	int ret = 0;// 函数调用返回值

	// 语音合成对象
	private SpeechSynthesizer mTts;

	// 默认发音人
	private String voicer = "xiaoyan";

	private String[] cloudVoicersEntries;
	private String[] cloudVoicersValue;

	// 缓冲进度
	private int mPercentForBuffering = 0;
	// 播放进度
	private int mPercentForPlaying = 0;

	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;

	private Toast mToast;
	private SharedPreferences mSharedPreferences;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			ChatMessage from = (ChatMessage) msg.obj;
			mDatas.add(from);
			mAdapter.notifyDataSetChanged();
			mChatView.setSelection(mDatas.size() - 1);
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);
		context = ChatActivity.this;
		SpeechUtility
				.createUtility(context, SpeechConstant.APPID + "=546088b0");

		// 初始化识别对象
		mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
		// 初始化听写Dialog,如果只使用有UI听写功能,无需创建SpeechRecognizer
		iatDialog = new RecognizerDialog(this, mInitListener);
		mSharedPreferences = getSharedPreferences(IatSettings.PREFER_NAME,
				Activity.MODE_PRIVATE);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		initView();

		// 初始化合成对象
		mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

		// 云端发音人名称列表
		cloudVoicersEntries = getResources().getStringArray(
				R.array.voicer_cloud_entries);
		cloudVoicersValue = getResources().getStringArray(
				R.array.voicer_cloud_values);

		mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME,
				Activity.MODE_PRIVATE);
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);

		mEngineType = SpeechConstant.TYPE_CLOUD;

		mAdapter = new ChatMessageAdapter(ChatActivity.this, mDatas);
		mChatView.setAdapter(mAdapter);

	}

	private void initView() {
		mChatView = (ListView) findViewById(R.id.message_list);
		mMsg = (EditText) findViewById(R.id.et_message);
		tv_yuying = (TextView) findViewById(R.id.tv_yuying);
		btn_yuying = (ImageButton) findViewById(R.id.btn_yuying);
		tv_yuying.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 设置参数
				setParam();
				boolean isShowDialog = mSharedPreferences.getBoolean(
						"iat_show", true);
				if (isShowDialog) {
					// 显示听写对话框
					iatDialog.setListener(recognizerDialogListener);
					iatDialog.show();
					showTip("开始说话...");
				} else {
					// 不显示听写对话框
					ret = mIat.startListening(recognizerListener);
					if (ret != ErrorCode.SUCCESS) {
						showTip("听写失败,错误码：" + ret);
					} else {
						showTip("开始说话...");
					}
				}
			}
		});

		mChatView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String text = mDatas.get(position).getMsg();
				System.out.println("------------" + text);
				// 设置参数
				setParam1();
				int code = mTts.startSpeaking(text, mTtsListener);
				if (code != ErrorCode.SUCCESS) {
					if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
						//未安装则跳转到提示安装页面
					}else {
						showTip("语音合成失败,错误码: " + code);	
					}
				}

			}
		});
		mDatas.add(new ChatMessage(ChatMessage.Type.INPUT, "你好，我是HerotCulb，很高兴为您服务", "", ""));
	}

	public void imbtnYuyin(View view) {
		if (isyuying) {
			mMsg.setVisibility(View.GONE);
			tv_yuying.setVisibility(View.VISIBLE);
			btn_yuying.setImageResource(R.drawable.keyboard);
			isyuying = false;
		} else {
			mMsg.setVisibility(View.VISIBLE);
			tv_yuying.setVisibility(View.GONE);
			btn_yuying.setImageResource(R.drawable.yuying);
			isyuying = true;
		}

	}

	/**
	 * 发送按钮
	 * 
	 * @param view
	 */
	public void sendMessage(View view) {
		final String msg = mMsg.getText().toString();
		sendMessage(msg);

	}

	private void sendMessage(final String msg) {
		if (TextUtils.isEmpty(msg)) {
			Toast.makeText(this, "空消息不能发送...", Toast.LENGTH_SHORT).show();
			return;
		}

		ChatMessage to = new ChatMessage(ChatMessage.Type.OUTPUT, msg,
				PreferenceUtils.getPrefString(ChatActivity.this,
						PreferenceUtils.USER_NAME, ""),
				PreferenceUtils.getPrefString(ChatActivity.this,
						PreferenceUtils.USER_IMAGE, ""));
		to.setDate(new Date());
		mDatas.add(to);

		mAdapter.notifyDataSetChanged();
		mChatView.setSelection(mDatas.size() - 1);

		mMsg.setText("");

		// 关闭软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// 得到InputMethodManager的实例
		if (imm.isActive()) {
			// 如果开启
			imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
					InputMethodManager.HIDE_NOT_ALWAYS);
			// 关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
		}

		new Thread() {
			public void run() {
				ChatMessage from = null;
				try {
					from = HttpUtils.sendMsg(msg);
				} catch (Exception e) {
					from = new ChatMessage(ChatMessage.Type.INPUT, "服务器连接中断...", "", "");
				}
				Message message = Message.obtain();
				message.obj = from;
				mHandler.sendMessage(message);
			};
		}.start();

	}

	/**
	 * 初始化监听器。
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败,错误码：" + code);
			}
		}
	};

	/**
	 * 听写监听器。
	 */
	private RecognizerListener recognizerListener = new RecognizerListener() {

		@Override
		public void onBeginOfSpeech() {
			showTip("开始说话");
		}

		@Override
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}

		@Override
		public void onEndOfSpeech() {
			showTip("结束说话");
		}

		@Override
		public void onResult(RecognizerResult results, boolean isLast) {
			String text = JsonParser.parseIatResult(results.getResultString());
			mResultText.append(text);
			mResultText.setSelection(mResultText.length());
			if (isLast) {
				// TODO 最后的结果
			}
		}

		@Override
		public void onVolumeChanged(int volume) {
			showTip("当前正在说话，音量大小：" + volume);
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
		}
	};

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			String text = JsonParser.parseIatResult(results.getResultString());
			System.out.println("----------text" + text);
			sendMessage(StringFilterUtil.StringFilter(text));
			// mResultText.append(text);
			// mResultText.setSelection(mResultText.length());
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			showTip(error.getPlainDescription(true));
		}

	};

	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}

	/**
	 * 参数设置
	 * 
	 * @param
	 * @return
	 */
	@SuppressLint("SdCardPath")
	public void setParam() {
		String lag = mSharedPreferences.getString("iat_language_preference",
				"mandarin");
		if (lag.equals("en_us")) {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
		} else {
			// 设置语言
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			// 设置语言区域
			mIat.setParameter(SpeechConstant.ACCENT, lag);
		}
		// 设置语音前端点
		mIat.setParameter(SpeechConstant.VAD_BOS,
				mSharedPreferences.getString("iat_vadbos_preference", "4000"));
		// 设置语音后端点
		mIat.setParameter(SpeechConstant.VAD_EOS,
				mSharedPreferences.getString("iat_vadeos_preference", "1000"));
		// 设置标点符号
		mIat.setParameter(SpeechConstant.ASR_PTT,
				mSharedPreferences.getString("iat_punc_preference", "1"));
		// 设置音频保存路径
		mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH,
				"/sdcard/iflytek/wavaudio.pcm");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时释放连接
		mIat.cancel();
		mIat.destroy();
		mTts.stopSpeaking();
		// 退出时释放连接
		mTts.destroy();
	}
	
	/**
	 * 初期化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
        		showTip("初始化失败,错误码："+code);
        	}		
		}
	};

	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			showTip("开始播放");
		}

		@Override
		public void onSpeakPaused() {
			showTip("暂停播放");
		}

		@Override
		public void onSpeakResumed() {
			showTip("继续播放");
		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			mPercentForBuffering = percent;
			mToast.setText(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
			
			mToast.show();
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			mPercentForPlaying = percent;
			showTip(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if(error == null)
			{
				showTip("播放完成");
			}
			else if(error != null)
			{
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
			
		}
	};

	/**
	 * 参数设置
	 * @param
	 * @return 
	 */
	private void setParam1(){
		
		//设置合成
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD))
		{
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			//设置发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME,voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			//设置发音人 voicer为空默认通过语音+界面指定发音人。
			mTts.setParameter(SpeechConstant.VOICE_NAME,"");
		}
		
		//设置语速
		mTts.setParameter(SpeechConstant.SPEED,mSharedPreferences.getString("speed_preference", "50"));

		//设置音调
		mTts.setParameter(SpeechConstant.PITCH,mSharedPreferences.getString("pitch_preference", "50"));

		//设置音量
		mTts.setParameter(SpeechConstant.VOLUME,mSharedPreferences.getString("volume_preference", "50"));
		
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,mSharedPreferences.getString("stream_preference", "3"));
	}

}
